package com.grandtech.insurance.common;

import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


/**
 * Created by boby on 2017/2/21.
 * base64加密
 */

public class Base64Util {


    public static byte[] decode(final byte[] bytes) {
        return Base64.decodeBase64(bytes);
    }

    /**
     * 二进制数据编码为BASE64字符串
     *
     * @param bytes
     * @return
     * @throws Exception
     */
    public static String encode(final byte[] bytes) {
        return new String(Base64.encodeBase64(bytes));
    }

    //编码
    public static String getBASE64(String s) {
        if (s == null) {
            return null;
        }
        return (new BASE64Encoder()).encode(s.getBytes());
    }

    //编码
    public static String getBASE64(String s, String f) {
        try {
            if (s == null) {
                return null;
            }
            return (new BASE64Encoder()).encode(s.getBytes(f));
        } catch (Exception e) {
            return null;
        }
    }

    //解码
    public static String getFromBASE64(String s) {
        if (s == null) return null;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] b = decoder.decodeBuffer(s);
            return new String(b);
        } catch (Exception e) {
            return null;
        }
    }

    //解码
    public static String getFromBASE64(String s, String f) {
        if (s == null) return null;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] b = decoder.decodeBuffer(s);
            return new String(b, f);
        } catch (Exception e) {
            return null;
        }
    }
}
